package com.tuanzi.loan.web.bean.family;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.bean.ViewScoped;

import lombok.Data;
import lombok.EqualsAndHashCode;

import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Charsets;
import com.tuanzi.loan.business.entity.family.ExternalPhoneRecord;
import com.tuanzi.loan.business.service.family.ExternalPhoneRecordService;
import com.tuanzi.loan.web.configuration.JSFInfoBean;

/**
 * 外部手机号导入处理
 * 
 * @author Xumiaohang 2017/11/17
 *
 */
@Data
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class ExternalPhoneRecordBean extends JSFInfoBean<ExternalPhoneRecord> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private ExternalPhoneRecordService externalPhoneRecordService;

	// 号码来源
	private String source;
	// 有效的总数量
	private int totalCount;
	// 重复的手机数量
	private int repeatCount;
	// 临时存储文件中全部数据
	private List<String> totalList;
	// 临时存储手机号的集合
	private List<String> phoneList;
	// 临时存储重复手机号的集合
	private List<String> repeatList;

	// 获取上传的文件
	public void handleExternalPhone(FileUploadEvent event) {
		try {
			totalList = IOUtils.readLines(event.getFile().getInputstream(),
					Charsets.UTF_8);
			//文件中手机号去重
			phoneList=new ArrayList<String>();
			for(String pho:totalList) {
	            if(!phoneList.contains(pho)){
	            	phoneList.add(pho);
	            }
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//校验文件
	public void onCheck(){
		//校验号码的有效性
		if (phoneList!=null && phoneList.size()>0) {
			Iterator<String> iterator = phoneList.iterator();
			while(iterator.hasNext()){
				if(iterator.next().trim().length()!=11){
					iterator.remove();
				}
			}
			totalCount=phoneList.size();
			repeatList = externalPhoneRecordService.repeatCheck(phoneList);
			repeatCount=repeatList.size();
			//去除重复的手机号
			phoneList.removeAll(repeatList);
			addInfoMessage("校验完成！");
		}else if(phoneList==null){
			 addWarnMessage("请先选择文件！");
		}
		
	}
	
	// 保存有效数据
	public void onSave() {
		 if (source != null && !"".equals(source.trim())) {
			 if (phoneList!=null && phoneList.size()>0) {
				 List<ExternalPhoneRecord> paramList=new ArrayList<ExternalPhoneRecord>();
				 for(String phone:phoneList){
					 $ = new ExternalPhoneRecord();
					 $.setPhone(phone);
					 $.setSource(source);
					 paramList.add($);
				 }
				 externalPhoneRecordService.saveOrUpdate(paramList);
				 addSuccessfullyMessage();
				 //重新初始化
				 totalCount=0;
				 repeatCount=0;
				 phoneList=null;
			 }else{
				 addWarnMessage("没有数据导入！");
			 }
		}else{
			addWarnMessage("请填写号码来源！");
		}

	}
}
